package com.ziqikeji.xianyan.controller.recommend;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ziqikeji.xianyan.common.DatagridDTO;
import com.ziqikeji.xianyan.entity.article.Article;
import com.ziqikeji.xianyan.entity.recommend.ArticleRecommend;
import com.ziqikeji.xianyan.service.article.ArticleService;
import com.ziqikeji.xianyan.service.recommend.ArticleRecommendService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.Id;
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by home on 2019/10/4.
 * @author cyy
 * 文章推荐
 */
@Controller
@RequestMapping(value = "admin/recommend")
public class ArticleRecommendController {
    @Autowired
    private ArticleService articleService;

    @Autowired
    private ArticleRecommendService articleRecommendService;

    /**
     * 获取为推荐，未删除文章列表
     */
    @ResponseBody
    @RequestMapping(value = "/ArticleRecommend/getList")
    public String getList(){
        //存放数据的数组
        JSONArray articleResList = new JSONArray();
        //获取所以文章集合
        List<Article> lists = this.articleService.getAll();
        for(int i = 0;i<lists.size();i++){
            //json数据，每循环一次，添加一个
            JSONObject res = new JSONObject();
            res.put("id",lists.get(i).getId());
            res.put("title",lists.get(i).getTitle());
            //循环结束后将j'son数据存放到数组中
            articleResList.add(res);
        }
        //将数组放入组装的json对象中
        return articleResList.toJSONString();
    }

    /**
     * 获取当前选中文章的作者
     */
    @ResponseBody
    @RequestMapping(value = "articleRecommend/getTitle/{id}")
    public String getTitle(@PathVariable("id") String id){
        JSONObject jsonObject = new JSONObject();
        Article article = this.articleService.get(id);
        String title = article.getWitter();
        ArticleRecommend articleRecommend = this.articleRecommendService.queryByArticle(article);
        if(articleRecommend!=null){
            jsonObject.put("error",id);
            return jsonObject.toJSONString();
        }else {
            jsonObject.put("title",title);
            return jsonObject.toJSONString();
        }
    }


    /**
     * 设置推荐页面
     * @return
     */
    @RequestMapping(value = "recommendInformation",method = RequestMethod.GET)
    public String CommendInformation() {
        return "/admin/recommend/article/edit";
    }

    /**
     * 文章推荐数据列表
     */
    @ResponseBody
    @RequestMapping(value = "articleRecommendList",method = RequestMethod.GET)
    public DatagridDTO getArticleRecommendList(@RequestParam(value = "pageNumber",required = false,defaultValue = "1") String pageNumber,
                                             @RequestParam(value = "pageSize",required = false,defaultValue = "10") String pageSize
    ){
        Page pageImpl = null;
        try{
            int page = 0;
            int size = 10;
            if (!StringUtils.isEmpty(pageNumber)) {
                page = Integer.parseInt(pageNumber) - 1;
                page = page < 0 ? 0 : page;
            }
            if (!StringUtils.isEmpty(pageSize)) {
                size = Integer.parseInt(pageSize);
                size = size < 0 ? 0 : size;
            }
            Page<ArticleRecommend> articlePage = this.articleRecommendService.getPage(page,size);
            PageRequest pageRequest = PageRequest.of(page,size);
            pageImpl = new PageImpl<>(articlePage.getContent(), pageRequest, articlePage.getTotalElements());

        }catch (Exception e){
            e.printStackTrace();
            return new DatagridDTO("获取失败，错误信息：" + e.getMessage(), 1, new ArrayList());
        }
        return new DatagridDTO("列表获取成功", 0, pageImpl.getTotalElements(), pageImpl.getContent());
    }


    /**
     * 图片上传的具体实现方法
     */
    @RequestMapping(value = "/recommendInformation/imgUpload",method = RequestMethod.POST)
    @ResponseBody
    public String handleFileUpload(@RequestParam("file")MultipartFile multipartFile,@RequestParam("id")String id){
        JSONObject result = new JSONObject();
        String pathString = null;
        if(!multipartFile.isEmpty()){
            try {
                String filePath = "E:\\xianyan\\recommend\\";
                File file = new File(filePath);
                if(!file.exists()){
                    //文件夹不存在则创建
                    file.mkdirs();
                }
                /*获取到上传的文件名*/
                String fileName = multipartFile.getOriginalFilename();
                String fileLName = fileName.substring(fileName.lastIndexOf(".") +1);
                File file1 = new File(filePath+id+"."+fileLName);
                BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file1));
                out.write(multipartFile.getBytes());
                out.flush();
                out.close();
                result.put("msg","ok");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                result.put("msg","error");
                return result.toJSONString();
            } catch (IOException e) {
                e.printStackTrace();
                result.put("msg","error");
                return result.toJSONString();
            }
            return result.toJSONString();
        }else {
            result.put("msg","error");
            return result.toJSONString();
        }
    }

    /**
     * 保存推荐数据
     */
    @ResponseBody
    @RequestMapping(value = "articleRecommend/articleInf",method = RequestMethod.POST)
    public ResponseEntity saveArticleInf(@RequestParam(value = "recommendedReason",required = false)String recommendedReason,
                                         @RequestParam(value = "indexShowImageUrl",required = false)String indexShowImageUrl,
                                         @RequestParam(value = "id",required = false)String id
                                        ){
        try{
            ArticleRecommend articleRecommend = new ArticleRecommend();
            Article article = this.articleService.get(id);
            articleRecommend.setArticle(article);
            articleRecommend.setIndexShowImageUrl(indexShowImageUrl);
            articleRecommend.setRecommendedReason(recommendedReason);
            this.articleRecommendService.save(articleRecommend);
        }catch (Exception e){
            return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity(HttpStatus.OK);
    }


    /**
     * 取消推荐
     */
    @RequestMapping(value = "cancelRecommend/{id}")
    public ResponseEntity cancelRecommend(@PathVariable("id")String id){
        try{
            ArticleRecommend articleRecommend = this.articleRecommendService.get(id);
            String path = articleRecommend.getIndexShowImageUrl();
            File file = new File(path);
            file.delete();
            this.articleRecommendService.delete(articleRecommend);
            return new ResponseEntity(HttpStatus.OK);
        }catch (Exception e){
            return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

}